package com.zudada.servermain.Service.ServiceImpl;

import com.zudada.servermain.POJO.DTO.LoginDTO;
import com.zudada.servermain.POJO.entity.PortUser;
import com.zudada.servermain.POJO.entity.User;
import com.zudada.servermain.Service.LoginService;
import com.zudada.servermain.common.constant.MessageConstant;
import com.zudada.servermain.exception.AccountNotFoundException;
import com.zudada.servermain.exception.PasswordErrorException;
import com.zudada.servermain.mapper.LoginMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper ;


    /**
     * 人员登陆
     * @param loginDTO
     * @return
     */
    public PortUser login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        //根据用户名查询数据库中的数据

        PortUser portUser = loginMapper.getByUsername(username);

        log.info("获得portUser数据:{}",portUser);

        //2.处理各种异常情况
        if(portUser==null){
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(portUser.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

       //返回实体对象

        return portUser;
    }

    @Override
    public User getRoleType(String userId) {
        User user = loginMapper.getByUserId(userId);
        log.info("用户数据:{}",user);
        return user;
    }
}
